package net.junaoki.persistence;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    private static final ThreadLocal<Session> threadLocalSession = new ThreadLocal<Session>();
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration conf = new Configuration();
            conf.addAnnotatedClass(Table1.class);

            return conf.configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static Session getCurrentSession(){
        Session session = threadLocalSession.get();
        if (session == null || !session.isOpen()) {
            session = sessionFactory.openSession();
            threadLocalSession.set(session);
        }
        return session;
    }

    public static void closeCurrentSession(){
        final Session session = threadLocalSession.get();
        if (session != null && session.isOpen()) {
           session.close();
        }
        threadLocalSession.set(null);
    }
 
}
